package TDAMapeo;
import TDALista.*;

public class MapeoConLista<K,V> implements TDAMapeo<K,V>{
	
	protected PositionList<Entrada<K,V>> entradas;
	
	public MapeoConLista(){
		entradas = new DoubleLinkedList<Entrada<K,V>> ();
	}

	public int size() {
		return entradas.size();
	}

	public boolean isEmpty() {
		return size() == 0;
	}
	
	public V get(K key) throws InvalidKeyException {
		if (key == null) throw new InvalidKeyException("get(): key nula");
		
		for(Entry<K,V> e : entradas){
			if(e.getKey().equals(key)){
			 return e.getValue();	
			}
		}
		return null;
		
	}

	public V put(K key, V value) throws InvalidKeyException {
		if(key == null) throw new InvalidKeyException("get(): key nula");
		
		for(Position<Entrada<K,V>> p : entradas.positions()){
			if(p.element().getKey().equals(key)){
				V aux = p.element().getValue();
				p.element().setValue(value);
				return aux;
			}
		}
		Entrada<K,V> nueva = new Entrada<K,V>(key,value);
		entradas.addLast(nueva);
		return null;
	}

	public V remove(K key) throws InvalidKeyException {
		if (key == null) throw new InvalidKeyException("remove():clave nula");
		
		for(Position<Entrada<K,V>> p : entradas.positions()){
			if(p.element().getKey().equals(key)){
				V aux = p.element().getValue();
				try{
				entradas.remove(p);} catch(Exception e){}
				return aux;
			}
		}
		
		return null;
	}

	
	public Iterable<K> keys() {
		PositionList<K> keys = new DoubleLinkedList<K>();
		for(Entrada<K,V> e : entradas ){
			keys.addLast(e.getKey());
		}
		return keys;
	}


	public Iterable<V> values() {
		PositionList<V> valores = new DoubleLinkedList<V>();
		for(Entrada<K,V> e : entradas){
			valores.addLast(e.getValue());
		}
		return valores;
	}


	public Iterable<Entry<K, V>> entries() {
		PositionList<Entry<K,V>> entries = new DoubleLinkedList<Entry<K,V>> ();
		for(Position<Entrada<K,V>> p : entradas.positions()){
			entries.addLast(p.element());
		}
		return entries;
	}
	
	
}
